<?php
require_once 'Zend/Db/Table/Abstract.php';

class UserFriendRequest extends Zend_Db_Table_Abstract {
	
	protected $_name = 'user_friend_request';
	protected $_primary = 'id';
	
	protected $_referenceMap = array(
		'User' => array(
			'columns' => 'user_id',
			'refTableClass' => 'User',
			'refColumns' => 'id'
		),
		'TargetUser' => array(
			'columns' => 'target_user_id',
			'refTableClass' => 'User',
			'refColumns' => 'id'
		),
		'Message' => array(
			'columns' => 'message_id',
			'refTableClass' => 'Message',
			'refColumns' => 'id'
		)
	);
	
	/**
	 * Find by user id and target user id.
	 * 
	 * @param $user_id
	 * @param $target_user_id
	 * @return return found object
	 */
	public static function findByUnique($user_id, $target_user_id) {
		$userFriendRequest = new UserFriendRequest();
		$select = $userFriendRequest->select()
		->where('user_id=?', $user_id)
		->where('target_user_id=?', $target_user_id);
		return $userFriendRequest->fetchRow($select);
	}
	
	/**
	 * Add or update user friend request.
	 * 
	 * @param $data
	 */
	public static function addFriendRequest($data) {
		$userFriendRequest = UserFriendRequest::findByUnique($data['user_id'], $data['target_user_id']);
		if (isset($userFriendRequest)) {
			$userFriendRequest->response = $data['response'];
			$userFriendRequest->approved_date = $data['approved_date'];
			return $userFriendRequest->save();
		} else {
			$userFriendRequest = new UserFriendRequest();
			return $userFriendRequest->insert($data);
		}
	}
}
?>